﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace LifeInSharePoint.Metro.Common.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:MetroThemeControl runat=server></{0}:MetroThemeControl>")]
    public class MetroThemeControl : WebControl
    {

        private const string DEFAULTSITELOGO = "/_layouts/LifeInSharePoint.Metro/images/blue/siteIcon.png";
        private const string DEFAULTSITECSS = "/_layouts/LifeInSharePoint.Metro/css/Blue.css";
        private const string METROACCORDIONJS = "/_layouts/LifeInSharePoint.Metro/js/MetroAccordion.js";
        private const string METROACCORDIONCLICKJS = "/_layouts/LifeInSharePoint.Metro/js/MetroAccordionClick.js";
        


        private bool LocallyStoredInheritedColourValue;
        private bool GlobalStoredAccordionValue;
        private bool LocallyStoredAccordionValue;
        private bool activateAccordion;
        private bool GloballyStoredFloatedRibbon;
        private bool GlobalUseThemeIcon;
        private string GlobalQuickLaunchPosition;
        private string GlobalAccordionTypeValue;

        private string ThemeCSS = string.Empty;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            Guid siteId = SPContext.Current.Site.ID;
            Guid webId = SPContext.Current.Web.ID;


            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                using (SPSite site = new SPSite(siteId))
                {
                    using (SPWeb web = site.OpenWeb(webId))
                    {

                        //The Root site cannot inherit from anywhere so check first.
                        if (web.IsRootWeb)
                        {
                            LocallyStoredInheritedColourValue = Convert.ToBoolean(Utilities.SPPropertyBagHelper.GetPropertyValue(web, "InheritMetroThemeColour"));
                        }

                        GlobalStoredAccordionValue = Convert.ToBoolean(Utilities.SPPropertyBagHelper.GetPropertyValue(site.RootWeb, "GlobalMetroAccordionActivated"));
                        GloballyStoredFloatedRibbon = Convert.ToBoolean(Utilities.SPPropertyBagHelper.GetPropertyValue(site.RootWeb, "GlobalMetroFloatedRibbon"));
                        GlobalUseThemeIcon = Convert.ToBoolean(Utilities.SPPropertyBagHelper.GetPropertyValue(site.RootWeb, "GlobalUseThemeIcon"));

                        GlobalAccordionTypeValue = Utilities.SPPropertyBagHelper.GetPropertyValue(web, "GlobalMetroAccordionType");

                        GlobalQuickLaunchPosition = Utilities.SPPropertyBagHelper.GetPropertyValue(site.RootWeb, "GlobalMetroQuickLaunchPosition");
                        LocallyStoredAccordionValue = Convert.ToBoolean(Utilities.SPPropertyBagHelper.GetPropertyValue(web, "MetroAccordionActivated"));
                        activateAccordion = GlobalStoredAccordionValue == true || LocallyStoredAccordionValue;


                        //If the Global Theme is set get the Value of the theme from the root site collection. Else use current sites theme.
                        ThemeCSS = LocallyStoredInheritedColourValue == true
                                       ? Utilities.SPPropertyBagHelper.GetPropertyValue(web.ParentWeb,
                                                                                        "MetroThemeColour")
                                       : Utilities.SPPropertyBagHelper.GetPropertyValue(web,
                                                                                        "MetroThemeColour");
                        ManageQuicklaunch(GlobalQuickLaunchPosition);
                        ManageTheme(ThemeCSS, web);
                        ManageAccordion(activateAccordion);
                        ManageRibbon();
                    }
                }
            });
        }

        private void ManageQuicklaunch(string GlobalQuickLaunchPosition)
        {
            if (GlobalQuickLaunchPosition != null)
                switch (GlobalQuickLaunchPosition)
                {
                    case "Left":
                        this.Controls.Add(new LiteralControl("<style>body #sideColumn{float:left;margin:0px 0px 0px 30px;}.rightpanel {margin:0px 20px 0px 272px !important; clear:right;}</style>"));
                        break;
                    case "Right":
                        this.Controls.Add(new LiteralControl("<style>body #sideColumn{float:right;margin:0px 20px 0px 0px;}.rightpanel {margin:0px 272px 0px 30px !important; clear:left;}</style>"));
                        break;
                }
        }



        private void ManageRibbon()
        {
            if (GloballyStoredFloatedRibbon)
            {
                //If Ribbon is to be floated then override theme style.
                this.Controls.Add(new LiteralControl("<style>body #ribbonWrapper {  position: fixed; top:0px; z-index:1000; width:100%; }#s4-bodyContainer {margin-top:80px;}</style>"));
            }
        }

        private void ManageAccordion(bool StoredAccordionValue)
        {
            if (StoredAccordionValue)
            {
                if (GlobalAccordionTypeValue == "Click")
                {
                    this.Controls.Add(new LiteralControl("<script type='text/javascript' src='" + SPContext.Current.Web.Url + METROACCORDIONCLICKJS + "'></script>"));
                }
                else
                {
                    this.Controls.Add(new LiteralControl("<script type='text/javascript' src='" + SPContext.Current.Web.Url + METROACCORDIONJS + "'></script>"));
                }
            }
        }

        private void ManageTheme(string StoredColourValue, SPWeb web)
        {
            try
            {

                if (string.IsNullOrEmpty(StoredColourValue))
                {
                    this.Controls.Add(new LiteralControl("<link rel='stylesheet' type='text/css' href='" + SPContext.Current.Web.Url + DEFAULTSITECSS + "'/>"));

                    if (GlobalUseThemeIcon)
                    {
                        web.AllowUnsafeUpdates = true;
                        web.SiteLogoUrl = DEFAULTSITELOGO;
                        web.Update();
                    }
                }
                else
                {
                    SPListItem _workItem = SPContext.Current.Site.RootWeb.Lists["Metro UI Themes"].GetItemById(Convert.ToInt32(StoredColourValue));
                    string cssUrl = _workItem["LISPCSSUrl"] == null ? string.Empty : _workItem["LISPCSSUrl"].ToString();
                    string siteIconUrl = _workItem["LISPSiteIconUrl"] == null ? string.Empty : _workItem["LISPSiteIconUrl"].ToString();
                    this.Controls.Add(new LiteralControl("<link rel='stylesheet' type='text/css' href='" + SPContext.Current.Web.Url + cssUrl + "'/>"));

                    if (GlobalUseThemeIcon)
                    {
                        web.AllowUnsafeUpdates = true;
                        web.SiteLogoUrl = siteIconUrl;
                        web.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                Label msg = new Label();
                msg.Text = ex.Message;
                this.Controls.Add(msg);
            }
        }
    }
}
